<?php

namespace IDock\Insurance\JTIC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\JTIC\Request\AllJTICRequest;
use IDock\Insurance\JTIC\Request\NonCar\NonCarInquiryRequest;
use IDock\Insurance\JTIC\Response\AllJTICResponse;
use IDock\Insurance\JTIC\Response\PolicyPaymentResponse;

class Builder implements BuilderInterface
{
    protected $config;

    protected $appId;

    protected $appKey;

    public function getConfig(): array
    {
        return $this->config;
    }

    public function execute(Request $request): Response
    {
        $requestId = sha1(uniqid('', true));

        /*** @var $request AllJTICRequest */
        $request->loadConfig($this->config);

        $request->setRequestId($requestId);

        $timestamp = date('YmdHis');

        $param = [
            'appId' => $this->appId,
            'method' => $request->getCode(),
            'timestamp' =>$timestamp,
            'bizContent' => ['Packet'=>$request->generate()]
        ];

        $request->setPreParameter($param);

        $this->sign($request);

        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        $preParameter = $request->getPreParameter();

        $bizContentXml = XMLTools::ToXML($preParameter['bizContent'],'');

        $preParameter['bizContent'] = $bizContentXml;

        ksort($preParameter);

        $toSignString = urldecode(http_build_query($preParameter)).'&appKey='.$this->appKey;

        //$toSignString = filter_var($toSignString,FILTER_SANITIZE_STRING);

        $sign = mb_strtolower(md5($toSignString));

        $preParameter['sign'] = $sign;

        $preParameter = XMLTools::ToXML([
            'appId' => $this->appId,
            'method' => $preParameter['method'],
            'timestamp' => $preParameter['timestamp'],
            'sign' => $sign,
            'bizContent' => "<![CDATA[$bizContentXml]]>"
        ],'');
        $preParameter = '<xml encoding="utf-8">'.$preParameter.'</xml>';

        $request->setBizParam($preParameter);

        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if (!$response->isSuccess()) {
            return $response;
        }

        $response->printerInit();
        return $response;
    }

    public function encrypt(Request $request)
    {
        // TODO: Implement encrypt() method.
    }
}


